package sk.marek.barak.server;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

import sk.marek.barak.client.Coment;
import sk.marek.barak.shared.Util;

public class CommentGAEDAO implements CommentDAO {

	@Override
	public Coment addComent(String text,String thoughtKey) {
		User user = UserServiceFactory.getUserService().getCurrentUser();
		
		Key parentKey = KeyFactory.stringToKey(thoughtKey);
		Key userKey = KeyFactory.createKey("UserInfo", user.getUserId());
		
		Entity userInfo = Util.findEntity(userKey);
		
		Entity entity = new Entity("Coment", parentKey);
		entity.setProperty("text", text);
		entity.setProperty("user",user.getUserId()); 
		Util.persistEntity(entity);
		System.out.println(entity.getKey().toString());
		
		Coment coment = new Coment(userInfo.getProperty("nickName").toString(),
				text,KeyFactory.keyToString(entity.getKey()));
		coment.setUserId(user.getUserId());
		return coment;
	}
	
	@Override
	public void removeComent(String key) {
		Key comentKey =KeyFactory.stringToKey(key);
		System.out.println(comentKey.toString());
		Util.deleteEntity(comentKey);

	}

	@Override
	public List<Coment> getThoughtComents(String thoughtKey) {
		List<Coment> coments = new ArrayList<Coment>();
		Iterable<Entity> entities = Util.listChildren("Coment", KeyFactory.stringToKey(thoughtKey));
		
		for(Entity entity : entities){
			Coment coment = new Coment(KeyFactory.keyToString(entity.getKey()));
			
			coment.setText(entity.getProperty("text").toString());
			Key userKey = KeyFactory.createKey("UserInfo",entity.getProperty("user").toString());
			Entity user = Util.findEntity(userKey);
			if(user==null){
				coment.setUser("Anonym");
			}else{
				coment.setUser(user.getProperty("nickName").toString());
			}
			coments.add(coment);
		}
		
		return coments;
	}

	@Override
	public void removeThoughtComents(String thoughtID) {
		Iterable<Entity> list = Util.listChildKeys("Coment",KeyFactory.stringToKey(thoughtID));
		for(Entity entity : list)
			Util.deleteEntity(entity.getKey());

	}


}
